<!--
 * @file 轨迹播放器组件
 * @description 轨迹回放控制器，负责UI展示和控制逻辑
 * @date 2024-08-21
 -->
<template>
  <div v-if="trackLoaded" class="trajectory-controller">
    <div class="info-panel">
      <!-- 当前时间显示 -->
      <div class="current-time-display">
        <span class="time-icon">⏱</span>
        <span id="currentTimeDisplay">{{ currentTime }}</span>
      </div>
      
      <!-- 时间范围选择器 -->
      <div class="time-range-selector">
        <div class="time-input-group">
          <div class="time-input-wrapper">
            <input 
              type="text" 
              class="time-input" 
              v-model="formattedStartTime" 
              @focus="startTimeSelectorHelper.handleFocus"
              @blur="startTimeSelectorHelper.handleBlur"
              @input="startTimeSelectorHelper.handleInput"
              @click="startTimeSelectorHelper.handleClick"
            >
            <div class="time-clock-icon">⏱</div>
            <!-- 开始时间下拉框 -->
            <div class="time-dropdown" v-if="showStartTimeDropdown" ref="startTimeDropdown">
              <div class="time-dropdown-column">
                <div 
                  v-for="hour in 24" 
                  :key="`start-hour-${hour-1}`" 
                  class="time-dropdown-item" 
                  :class="{ active: getHourFromTime(formattedStartTime) === hour-1 }"
                  @click="selectStartHour(hour-1)"
                >
                  {{ String(hour-1).padStart(2, '0') }}
                </div>
              </div>
              <div class="time-dropdown-column">
                <div 
                  v-for="minute in 60" 
                  :key="`start-minute-${minute-1}`" 
                  class="time-dropdown-item" 
                  :class="{ active: getMinuteFromTime(formattedStartTime) === minute-1 }"
                  @click="selectStartMinute(minute-1)"
                >
                  {{ String(minute-1).padStart(2, '0') }}
                </div>
              </div>
            </div>
          </div>
          <span class="time-separator">-</span>
          <div class="time-input-wrapper">
            <input 
              type="text" 
              class="time-input" 
              v-model="formattedEndTime"
              @focus="endTimeSelectorHelper.handleFocus"
              @blur="endTimeSelectorHelper.handleBlur"
              @input="endTimeSelectorHelper.handleInput"
              @click="endTimeSelectorHelper.handleClick"
            >
            <div class="time-clock-icon">⏱</div>
            <!-- 结束时间下拉框 -->
            <div class="time-dropdown" v-if="showEndTimeDropdown" ref="endTimeDropdown">
              <div class="time-dropdown-column">
                <div 
                  v-for="hour in 24" 
                  :key="`end-hour-${hour-1}`" 
                  class="time-dropdown-item" 
                  :class="{ active: getHourFromTime(formattedEndTime) === hour-1 }"
                  @click="selectEndHour(hour-1)"
                >
                  {{ String(hour-1).padStart(2, '0') }}
                </div>
              </div>
              <div class="time-dropdown-column">
                <div 
                  v-for="minute in 60" 
                  :key="`end-minute-${minute-1}`" 
                  class="time-dropdown-item" 
                  :class="{ active: getMinuteFromTime(formattedEndTime) === minute-1 }"
                  @click="selectEndMinute(minute-1)"
                >
                  {{ String(minute-1).padStart(2, '0') }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 显示范围开关 -->
        <div class="range-toggle-container" @click="clickToggleRange">
          <label class="toggle-switch">
            <input type="checkbox" :checked="showRangeSelection" @change="handleRangeToggle">
            <span 
              class="slider"
              :style="sliderStyle"
            >
              <span class="slider-thumb" :style="sliderThumbStyle"></span>
            </span>
          </label>
          <span class="toggle-label">显示范围</span>
        </div>
      </div>
      
      <!-- 距离信息 -->
      <div class="time-distance-info">
        <div class="info-item">
          <span>距离:</span>
          <span>{{ formattedDistance }}</span>
        </div>
      </div>
    </div>

    <div class="controls-container">
      <!-- 控制按钮组 -->
      <div class="control-buttons">
        <button class="control-btn" :class="{ active: isPlaying }" @click="togglePlay" title="播放/暂停">
          {{ isPlaying ? '⏸' : '▶' }}
        </button>
        <button class="control-btn" @click="previousFrame" title="后退10分钟">⏮</button>
        <button class="control-btn" @click="nextFrame" title="前进10分钟">⏭</button>
      </div>

      <!-- 速度控制 -->
      <div class="speed-control">
        <span class="speed-label">速度:</span>
        <select class="speed-select" v-model="currentSpeed" @change="handleSpeedChange">
          <option value="0.5">0.5x</option>
          <option value="1">1x</option>
          <option value="2">2x</option>
          <option value="5">5x</option>
        </select>
      </div>

      <!-- 时间轴 -->
      <div class="timeline-container">
        <div class="timeline-markers" id="timelineMarkers">
          <div v-for="hour in 25" :key="hour-1" class="hour-marker" :class="{ active: isCurrentHour(hour-1) }">
            {{ hour - 1 }}
          </div>
        </div>
        <div class="timeline" @click="seekToPosition" @touchstart.prevent="seekToPositionTouch">
          <div class="timeline-range-selection" v-if="showRangeSelection" :style="rangeSelectionStyle"></div>
          <div class="timeline-progress" :style="{ width: progressPercentage + '%' }"></div>
          <div class="timeline-handle" :style="{ left: progressPercentage + '%' }" tabindex="0" 
               @mousedown="startDrag($event, 'main')"
               @touchstart.prevent="startDragTouch($event, 'main')"></div>
          <div class="range-handle start" v-if="showRangeSelection" :style="{ left: startTimePercentage + '%' }" tabindex="0"
               @mousedown="startDrag($event, 'rangeStart')"
               @touchstart.prevent="startDragTouch($event, 'rangeStart')"></div>
          <div class="range-handle end" v-if="showRangeSelection" :style="{ left: endTimePercentage + '%' }" tabindex="0"
               @mousedown="startDrag($event, 'rangeEnd')"
               @touchstart.prevent="startDragTouch($event, 'rangeEnd')"></div>
          <div class="time-tooltip" :style="tooltipStyle">{{ tooltipText }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { useTrackPlayer } from '@/hooks/monitor/useTrackPlayer';
import { useDragControl } from '@/hooks/monitor/useDragControl';
import { useTimeSelector, getHourFromTime, getMinuteFromTime } from '@/hooks/monitor/useTimeSelector';
import type { TimeTooltipStyle, TrackPlayerProps, DragType } from '@/types/player';

// 组件属性
const props = withDefaults(defineProps<TrackPlayerProps>(), {
  trackLoaded: false,
  currentTime: '00:00',
  formattedDistance: '0 km',
  isPlaying: false,
  autoPlay: false,
  distance: 0
});

// 组件事件
const emit = defineEmits<{
  (e: 'play'): void;
  (e: 'pause'): void;
  (e: 'seek', percentage: number): void;
  (e: 'speed-change', speed: number): void;
  (e: 'range-change', startPercentage: number, endPercentage: number): void;
  (e: 'toggle-range', show: boolean): void;
}>();

// 初始化时间选择器
const {
  // 状态
  formattedStartTime,
  formattedEndTime,
  startTimePercentage,
  endTimePercentage,
  
  // 下拉选择器状态
  showStartTimeDropdown,
  showEndTimeDropdown,
  
  // 选择器助手
  startTimeSelectorHelper,
  endTimeSelectorHelper,
  
  // 工具方法
  timeToPercentage,
  percentageToTime,
  updateStartTimePercentage,
  updateEndTimePercentage,
  
  // 方法 - 下拉框控制
  toggleStartTimeDropdown,
  toggleEndTimeDropdown,
  closeStartTimeDropdown,
  closeEndTimeDropdown,
  closeAllDropdowns,
  
  // 方法 - 时间选择
  selectStartHour,
  selectStartMinute,
  selectEndHour,
  selectEndMinute,
} = useTimeSelector({
  enableRange: true,
  initialStartTime: '00:00',
  initialEndTime: '23:59',
  minTimeDifference: 1,
  onTimeChange: (type, time, percentage) => {
    // 当时间变化时触发范围变更事件
    emitRangeChangeEvent();
  }
});

// 时间格式正则
const timePattern = /^([0-1]?[0-9]|2[0-3]):([0-5][0-9])$/;

// 使用轨迹播放器Hook
const {
  // 状态
  currentSpeed,
  progressPercentage,
  formattedCurrentTime,
  
  // 范围选择状态
  showRangeSelection,
  rangeSelectionStyle,
  
  // 样式对象
  sliderStyle,
  sliderThumbStyle,
  
  // 方法 - 播放控制
  togglePlay: hookTogglePlay,
  nextFrame,
  previousFrame,
  changeSpeed,
  isCurrentHour,
  
  // 方法 - 跳转
  seekToPosition,
  seekToPositionTouch,
  
  // 方法 - 范围控制
  toggleRangeDisplay,
  clickToggleRange,
  handleRangeToggle,
} = useTrackPlayer({
  autoPlay: props.autoPlay,
  enableRangeSelection: true,
  initialSpeed: 1
});

// 使用拖动控制Hook
const {
  // 状态
  isDragging,
  dragType,
  tooltipText,
  tooltipStyle,
  
  // 方法 - 拖动控制
  startDrag,
  startDragTouch,
  stopDrag,
  stopDragTouch,
  
  // 方法 - 提示控制
  showTooltip
} = useDragControl({
  // 拖动开始回调
  onDragStart: (type, event) => {
    // 可以在这里添加额外的拖动开始逻辑
    console.log(`开始拖动: ${type}`);
  },
  
  // 拖动中回调
  onDrag: (percentage, type, containerElement) => {
    // 根据拖动类型更新不同状态
    if (type === 'main') {
      progressPercentage.value = percentage;
      // 通知轨迹图层进行位置更新
      emit('seek', percentage);
    } else if (type === 'rangeStart') {
      // 确保开始时间不超过结束时间减去最小间隔(1分钟)
      const minDistancePercentage = (1 / (24 * 60)) * 100; // 1分钟占总时长的百分比
      const maxStartPercentage = endTimePercentage.value - minDistancePercentage;
      
      // 限制开始时间百分比在有效范围内
      startTimePercentage.value = Math.min(Math.max(0, percentage), maxStartPercentage);
      
      // 更新开始时间显示
      const time = percentageToTime(startTimePercentage.value);
      formattedStartTime.value = time;
    } else if (type === 'rangeEnd') {
      // 确保结束时间不小于开始时间加上最小间隔(1分钟)
      const minEndDistancePercentage = (1 / (24 * 60)) * 100; // 1分钟占总时长的百分比
      const minEndPercentage = startTimePercentage.value + minEndDistancePercentage;
      
      // 限制结束时间百分比在有效范围内
      endTimePercentage.value = Math.max(Math.min(100, percentage), minEndPercentage);
      
      // 更新结束时间显示
      const time = percentageToTime(endTimePercentage.value);
      formattedEndTime.value = time;
    }
  },
  
  // 拖动结束回调
  onDragEnd: (type) => {
    if (type === 'rangeStart' || type === 'rangeEnd') {
      // 范围变更结束，发送事件
      emitRangeChangeEvent();
    }
  },
  
  // 获取提示文本
  getTooltipText: (type, percentage) => {
    return percentageToTime(percentage);
  },
  
  // 传递自定义数据（可选）
  data: {
    progressPercentage: progressPercentage.value,
    startTimePercentage: startTimePercentage.value,
    endTimePercentage: endTimePercentage.value
  }
});

/**
 * 发送范围变更事件
 */
function emitRangeChangeEvent() {
  emit('range-change', startTimePercentage.value, endTimePercentage.value);
}

/**
 * 切换播放/暂停状态
 */
function togglePlay() {
  hookTogglePlay();
  emit(props.isPlaying ? 'pause' : 'play');
}

/**
 * 改变播放速度
 */
function handleSpeedChange() {
  emit('speed-change', parseFloat(currentSpeed.value));
  changeSpeed();
}

// 监听范围变化，通知父组件
watch([startTimePercentage, endTimePercentage], ([startVal, endVal]) => {
  emit('range-change', startVal, endVal);
}, { deep: true });

// 监听范围显示切换
watch(showRangeSelection, (newVal: boolean) => {
  emit('toggle-range', newVal);
});

// 监听进度变化
watch(progressPercentage, (newVal: number) => {
  emit('seek', newVal);
});

// 暴露组件方法
defineExpose({
  progressPercentage,
  startTimePercentage,
  endTimePercentage,
  formattedStartTime,
  formattedEndTime
});
</script>

<style lang="scss">
@import './styles/track-player.scss';
</style> 